package com.company;

/**
 * Created by Administrator on 2016/10/23.
 */
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;

import java.io.*;

class ManageExcel {
    public XSSFWorkbook workbook = new XSSFWorkbook();//创建Excel文件(Workbook)
    public XSSFSheet sheet = workbook.createSheet("sheet0");//创建工作表


    public Cell createCell(int row, int col, String n) {
        XSSFRow row0 = sheet.createRow(row);
        XSSFCell cell = row0.createCell(col);
        cell.setCellValue(n);
        return cell;
    }
    public Cell createCell(int row, int col, double n) {
        XSSFRow row0 = sheet.createRow(row);
        XSSFCell cell = row0.createCell(col);
        cell.setCellValue(n);
        return cell;
    }

    public Cell setFormula(int row, int col) {

        XSSFCell cell= sheet.getRow(row).createCell(col);
        cell.setCellFormula("sum(C1:C5)");                //设置公式,计算和
        return cell;

    }
    public Cell setFormat(int row,int col,double n){
        Cell cell=createCell(row,col,n);
        XSSFCellStyle style = workbook.createCellStyle();
        style.setDataFormat(workbook.createDataFormat().getFormat("￥0.00"));
        cell.setCellStyle(style);                       //设置单元格中数据格式
        return cell;
    }
    public Cell together(int row1,int row2,int col1,int col2,String n){
        Cell cell = createCell(row1,col1,n);
        CellRangeAddress region=new CellRangeAddress(row1,row2,col1,col2);
        sheet.addMergedRegion(region);
        return cell;
    }
    public Cell Middle(int row,int col,String n){
        Cell cell=createCell(row,col,n);
        XSSFCellStyle style=workbook.createCellStyle();
        if(n=="水平居中") {
            style.setAlignment(XSSFCellStyle.ALIGN_CENTER);//水平居中
        }
        else if(n=="垂直居中") {
            style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);//垂直居中
        }
        cell.setCellStyle(style);
        return cell;
    }
    public void close(){
        try {
            String filePath = "src/test.xlsx";
            FileOutputStream out = new FileOutputStream(filePath);
            workbook.write(out);                       //保存Excel文件
            out.close();                               //关闭文件流
        }catch(Exception e)
        {
        }

    }
}
